package com.woniu.repaircenter.service.consumer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.repaircenter.service.config.RabbitMQConfig;
import com.woniu.repaircenter.service.mapper.RepairNoticeMapper;
import com.woniu.repaircenter.service.model.RepairNotice;
import com.woniu.repaircenter.service.service.RepairNoticeService;
import com.woniu.server.RedisKey;
import com.woniu.server.RedisUtil;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class NoticeViewConsumer {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RepairNoticeMapper repairNoticeMapper;


    /**
     * 监听 RabbitMQ 队列中的消息并更新维修通知的浏览次数
     * @param productViews 包含产品浏览量的映射，键为产品ID，值为浏览次数
     */
    @RabbitListener(queues = RabbitMQConfig.QUEUE_NAME)
    public void receiveMessage(Map<String, Integer> productViews) {
        // 遍历接收到的浏览量信息
        for (Map.Entry<String, Integer> entry : productViews.entrySet()) {
            String noticeId = entry.getKey();
            Integer viewCount = entry.getValue();
            // 创建 RepairNotice 对象并设置属性
            RepairNotice repairNotice = new RepairNotice();
            repairNotice.setNoticeId(Long.valueOf(noticeId));
            repairNotice.setBrowseTimes(viewCount);
            // 保存或更新浏览量到数据库
            repairNoticeMapper.updateNoticeStatus(repairNotice);
            // 删除 Redis 中的浏览量数据
            String redisKey = RedisKey.noticeView(noticeId.toString());
            redisUtil.del(redisKey);
        }
    }
}
